   package com.javalong.affairs.module.recycle.activity;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.javalong.affairs.R;
import com.javalong.affairs.base.activity.UIHandlerActivity;
import com.javalong.affairs.base.common.ServiceLocator;
import com.javalong.affairs.base.common.UIHandler;
import com.javalong.affairs.base.constant.BundleKey;
import com.javalong.affairs.base.constant.DataType;
import com.javalong.affairs.base.constant.RequestCode;
import com.javalong.affairs.base.constant.RequestKey;
import com.javalong.affairs.base.listener.BaseResponseListener;
import com.javalong.affairs.base.model.MessageInfo;
import com.javalong.affairs.base.model.User;
import com.javalong.affairs.base.ui.TextSelectView;
import com.javalong.affairs.base.ui.TextSelectView.OnImageClick;
import com.javalong.affairs.base.ui.TopTitle;
import com.javalong.affairs.base.utils.HttpUtils;
import com.javalong.affairs.base.utils.StringUtils;
import com.javalong.affairs.base.utils.TimeUtils;
import com.javalong.affairs.base.utils.ToastUtils;
import com.javalong.affairs.base.utils.UrlUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

@ContentView(R.layout.activity_msgdetail)
public class MsgRecycleDetailActivity extends UIHandlerActivity implements
		OnItemSelectedListener, OnClickListener, OnImageClick {
	@ViewInject(R.id.tv_time)
	private TextView tv_time;
	@ViewInject(R.id.tv_address)
	private TextView tv_address;
	@ViewInject(R.id.tv_sender)
	private TextView tv_sender;
	@ViewInject(R.id.ll_receiver)
	private LinearLayout ll_receiver;
	@ViewInject(R.id.ui_tsview_delegate)
	private TextSelectView tsview_delegate;
	@ViewInject(R.id.sp_operation)
	private Spinner sp_operation;
	@ViewInject(R.id.tv_content)
	private TextView tv_content;
	@ViewInject(R.id.tv_timelimit)
	private TextView tv_timelimit;
	@ViewInject(R.id.ui_toptitle)
	private TopTitle topTitle;
	@ViewInject(R.id.tv_title_content)
	private TextView tv_title;
	@ViewInject(R.id.ll_delegator)
	private LinearLayout ll_delegator;
	@ViewInject(R.id.ll_leave)
	private LinearLayout ll_leave;
	@ViewInject(R.id.et_delegator_why)
	private EditText et_delegator_why;
	@ViewInject(R.id.et_leave_why)
	private EditText et_leave_why;
	@ViewInject(R.id.bt_ok)
	private Button bt_ok;
	@ViewInject(R.id.bt_file)
	private Button bt_file;
	@ViewInject(R.id.bt_delete)
	private Button bt_delete;
	private StringBuilder receiverStr = new StringBuilder();
	private StringBuilder receiverNameStr = new StringBuilder();
	private String msgId;
	private int type = 0;
	private String simpleMsgId;
	private String downloadFilePath;
	private MessageInfo msgInfo;
	private boolean nodelete;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		Bundle bundle = getIntent().getBundleExtra(BundleKey.BUNDLE);
		msgId = bundle.getString(BundleKey.MSGID);
		simpleMsgId = bundle.getString(BundleKey.SIMPLEMSGID);
		nodelete = bundle.getBoolean(BundleKey.NODELETE);
		bt_delete.setVisibility(View.GONE);
		initData();
		initSpinner();
	}

	private void initSpinner() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, new String[] { "已读", "确定",
						"委托", "请假" });
		sp_operation.setAdapter(adapter);
		sp_operation.setOnItemSelectedListener(this);
	}

	private void initData() {
		String url = UrlUtils.getUrl("SendMessage", "outOne_messageinfo");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(RequestKey.ID, simpleMsgId);
		HttpUtils.post(url, params, new BaseResponseListener(DataType.MESSAGE) {
			@Override
			public void onSuccess(Object obj) {
				super.onSuccess(obj);
				initUI((MessageInfo) obj);
			}
		});
	}

	private void initUI(MessageInfo msgInfo) {
		if (msgInfo != null) {
			this.msgInfo = msgInfo;
			tv_time.setText(TimeUtils.getFormatTime2(Long
					.parseLong(msgInfo.time)));
			tv_address.setText(msgInfo.place);
			tv_sender.setText(msgInfo.nameSend);
			tv_content.setText(msgInfo.messageData);
			tv_timelimit.setText(msgInfo.timeLimit);
			tv_title.setText(msgInfo.title);
			bt_ok.setOnClickListener(this);
			bt_delete.setOnClickListener(this);
			tsview_delegate.setOnImageClick(this);
			bt_file.setOnClickListener(this);
			bt_ok.setVisibility(View.GONE);
		}
		topTitle.setOnLeftDrawableClick(this);
		if (msgInfo.receiveStatus != 0) {
			switch (msgInfo.receiveStatus) {
			case 1:
				sp_operation.setSelection(0);
				break;
			case 2:
				sp_operation.setSelection(2);
				break;
			case 3:
				sp_operation.setSelection(1);
				break;
			}

		}

		if (msgInfo.receiveStatus == 1 || msgInfo.receiveStatus == 3) {
			sp_operation.setEnabled(false);
			bt_ok.setEnabled(false);
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		type = position;
		switch (position) {
		case 0:
			ll_delegator.setVisibility(View.GONE);
			ll_leave.setVisibility(View.GONE);
			ll_receiver.setVisibility(View.GONE);
			break;
		case 1:
			ll_delegator.setVisibility(View.GONE);
			ll_leave.setVisibility(View.GONE);
			ll_receiver.setVisibility(View.GONE);
			break;
		case 2:
			ll_delegator.setVisibility(View.VISIBLE);
			ll_leave.setVisibility(View.GONE);
			ll_receiver.setVisibility(View.VISIBLE);
			break;
		case 3:
			ll_delegator.setVisibility(View.GONE);
			ll_leave.setVisibility(View.VISIBLE);
			ll_receiver.setVisibility(View.GONE);
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
	}

	@Override
	public void onClick(View v) {
		String url = null;
		super.onClick(v);
		switch (v.getId()) {
		case R.id.bt_ok:
			progressDialog.show();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put(RequestKey.ID, simpleMsgId);
			switch (type) {
			case 0:
				url = UrlUtils.getUrl("SendMessage", "read");
				break;
			case 1:
				url = UrlUtils.getUrl("SendMessage", "affirm");
				break;
			case 2:
				url = UrlUtils.getUrl("SendMessage", "entrust");
				params.put(RequestKey.NAMELIST, receiverStr);
				params.put(RequestKey.REASON, et_delegator_why.getText());
				break;
			case 3:
				url = UrlUtils.getUrl("SendMessage", "leave");
				params.put(RequestKey.REASON, et_leave_why.getText());
				break;
			}

			HttpUtils.post(url, params, new BaseResponseListener(null) {
				@Override
				public void onSuccess(Object obj) {
					super.onSuccess(obj);
					progressDialog.dismiss();
					UIHandler uiHandler = ServiceLocator.GetInstance()
							.getInstance(UIHandler.class);
					uiHandler.postCallback(
							R.string.event_refresh_notification_receive, null);
					finish();
				}
			});
			break;
		case R.id.bt_file:
			if (msgInfo != null && msgInfo.attachment != null
					&& msgInfo.attachment.size() > 0
					&& !StringUtils.isEmpty(msgInfo.attachment.get(0).download)) {
				downloadFilePath = StringUtils.getRandomFilePath();
				download(msgInfo.attachment.get(0).download, downloadFilePath);
			}
			break;
		case R.id.bt_delete:
			delete();
			break;
		}
	}

	private void delete() {
		String url = UrlUtils.getUrl("SendMessage", "delete");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(RequestKey.ID, msgInfo.id);
		HttpUtils.post(url, params, new BaseResponseListener(null) {
			@Override
			public void onSuccess(Object obj) {
				super.onSuccess(obj);
				ToastUtils.showMessage("删除成功");
				UIHandler uiHandler = ServiceLocator.GetInstance().getInstance(
						UIHandler.class);
				uiHandler.postCallback(
						R.string.event_refresh_notification_receive, null);
				finish();
			}
		});
	}

	public void download(String url, String path) {
		com.lidroid.xutils.HttpUtils http = new com.lidroid.xutils.HttpUtils();
		http.download(url, path, true, true, new RequestCallBack<File>() {

			public void onStart() {
				bt_file.setText("正在连接...");
				bt_file.setClickable(false);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				bt_file.setText(current + "/" + total);
				bt_file.setClickable(false);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				bt_file.setText("重新下载");
				bt_file.setClickable(true);
			}

			@Override
			public void onSuccess(ResponseInfo<File> responseInfo) {
				bt_file.setText("打开");
				bt_file.setClickable(true);
				bt_file.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						File file = new File(downloadFilePath);
						if (file.exists() && file.isFile()) {
							openFile(file);
						} else {
							ToastUtils.showMessage("文件不存在或已损坏");
						}
					}
				});

			}
		});

	}

	private void openFile(File f) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);

		String type = getMIMEType(f);
		intent.setDataAndType(Uri.fromFile(f), type);
		startActivity(intent);
	}

	private String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else {
			type = "*";
		}
		type += "/*";
		return type;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case RequestCode.DELEGATE:
				User user = (User) data.getSerializableExtra(BundleKey.USER);
				receiverStr.append(user.userName);
				receiverNameStr.append(user.name);
				tsview_delegate.setText(receiverNameStr.toString());
				break;
			}
		}
	}
}
